package org.mao.quartz;

import java.util.List;

import org.apache.log4j.Logger;
import org.joda.time.LocalDateTime;
import org.mao.forum.service.ForumPostService;
import org.mao.forum.service.ForumTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.DefaultManagedTaskScheduler;

public class QuartzManager {

	private static Logger logger = Logger.getLogger(QuartzManager.class);

	@Autowired
	private ForumTaskService forumTaskService;

	@Autowired
	private ForumPostService forumPostService;

	public void init() {
		try {
			logger.info("QuartzManager start init scheduler...............");
			LocalDateTime nowTime = new LocalDateTime();
			nowTime = nowTime.plusSeconds(5);
			TaskScheduler schedule = new DefaultManagedTaskScheduler();
			//启动一个扫描任务表，并创建定时任务的任务
			schedule.scheduleAtFixedRate(new Runnable() {
				@Override
				public void run() {
					//logger.info("scan available task...............");
					forumTaskService.queryAvailableTask();
				}
			}, nowTime.toDate(), 5000);

			nowTime = nowTime.plusSeconds(60);
			// 启动一个初始化帖子种子信息的任务
			schedule.scheduleWithFixedDelay(new Runnable() {
				@Override
				public void run() {
					List<Integer> postList = forumPostService.queryUnFoundTorrentUrl();
					for (Integer postId : postList) {
						forumPostService.reReadTorrentUrl(postId);
					}
					postList = forumPostService.queryUnFoundImage();
					for (Integer postId : postList) {
						forumPostService.reReadImageList(postId);
					}
				}
			}, nowTime.toDate(), 36000000);
			logger.info("QuartzManager end init scheduler...............");
		} catch (Exception e) {
			logger.error("", e);
		}
	}

	public void execute() {
		try {
			logger.info("QuartzManager start job...............");
			logger.info("QuartzManager end job...............");
		} catch (Exception e) {
			logger.error("", e);
		}
	}
}
